import json
import traceback

from flask import current_app as app, request

from app import celery_app
from app.celery.tasks import (
    SYNC_FUNC,
    repeat_celery_tasks,
)
from app.auth import permission_required
from app.libs.redprint import RedPrint
from app.libs.enums import NotificationTarget, TaskName
from app.celery.tasks import load_scan_events_for_scanv
from app.errors import (
    Success,
    ScannerAPIException
)
from app.celery.tasks import RECEIVE_NOTIFY

api = RedPrint("notify")


@api.route("", methods=["POST"])
@permission_required("admin")
def notify():
    request_args = json.loads(request.data)
    # no addition
    if not request_args.get('task', {}).get('addition'):
        return Success()
    # no used
    notify_type = request_args.get('notify_type_name')
    if not RECEIVE_NOTIFY.get(notify_type):
        return Success()
    app.logger.info(request_args)

    addition = request_args.get('task', {}).get('addition', {})
    notification_target = addition.pop("notificationTarget", NotificationTarget.SCANV.value)
    if notification_target == NotificationTarget.EASM.value:
        celery_app.send_task(TaskName.LOAD_SCAN_EVENTS_FOR_EASM.value, args=(request_args,))
        return Success()
    if app.config.get("DEBUG", False):
        load_scan_events_for_scanv(request_args)
        return Success()
    if notification_target == NotificationTarget.SCANV.value:
        celery_app.send_task(TaskName.LOAD_SCAN_EVENTS_FOR_SCANV.value, args=(request_args,))
    return Success()


@api.route('/sync_result/<string:sync_type>', methods=['POST'])
@permission_required('admin')
def sync_notice(sync_type):
    try:
        if func := SYNC_FUNC.get(sync_type):
            func()
            return Success()

        return Success(msg=f"Function '{sync_type}' not found.")
    except ScannerAPIException as e:
        app.logger.exception(e)
        traceback.print_exc()
        return ScannerAPIException()
    except Exception as e:
        app.logger.exception(e)
        traceback.print_exc()
        return Success()


@api.route('/celery/task/fix', methods=['POST'])
@permission_required('admin')
def repeat_task():
    request_args = json.loads(request.data)
    iso_low = request_args.get('iso_low')
    iso_high = request_args.get('iso_high')
    send_alert = request_args.get('send_alert')
    task_type = request_args.get('task_type')
    is_latest = request_args.get('is_latest')

    repeat_celery_tasks.delay(iso_low, iso_high, task_type, send_alert, is_latest)
    return Success()
